package com.sunxd.zstudy.juc;

import java.util.concurrent.Semaphore;

/**
 * @author: 信号灯
 * 限流 - 谁拿到许可，谁才可以执行
 *
 * @date: 2021-04-02 15:37
 **/
public class T13_Semaphore {
    public static void main(String[] args) {
        // 允许 （x） 一个线程同时执行
        Semaphore semaphore = new Semaphore(1);
//        Semaphore semaphore = new Semaphore(1,true);
        new Thread(()->{
            try {
                semaphore.acquire();
                System.out.println("T1 is running");
                Thread.sleep(1000);
                System.out.println("T1 is running");
                Thread.sleep(2000);
                System.out.println("T1 is running");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                semaphore.release();
            }
        }).start();

        new Thread(()->{
            try {
                semaphore.acquire();
                System.out.println("T2 is running");
                Thread.sleep(1000);
                System.out.println("T2 is running");
                Thread.sleep(2000);
                System.out.println("T2 is running");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                semaphore.release();
            }
        }).start();
        new Thread(()->{
            try {
                semaphore.acquire();
                System.out.println("T3 is running");
                Thread.sleep(1000);
                System.out.println("T3 is running");
                Thread.sleep(2000);
                System.out.println("T3 is running");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                semaphore.release();
            }
        }).start();

    }
}
